package com.dangdang.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dangdang.domain.User;
import com.dangdang.util.EmailUtils;
import com.dangdang.util.HbnUtils;
import com.dangdang.util.MD5Utils;
import com.dangdang.util.VerifyCodeUtils;

/**
 * 用户类业务层
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-25
 */
public class AuthorizeServiceImpl implements AuthorizeService {

	/**
	 * 添加一个用户
	 */
	public void addUser(User user) {
		Session session = HbnUtils.getSession();
		Transaction tx = session.beginTransaction();
		// 对密码加密
		user.setPassword(MD5Utils.md5(user.getPassword()));

		user.setVerify(false);
		user.setUserIntegral(0);
		session.save(user);
		String content = VerifyCodeUtils.generateCode(user.getId());
		EmailUtils.sendEmail(user.getEmail(), content);
		user.setVerifyCode(VerifyCodeUtils.getCode(content));
		tx.commit();
		session.close();
	}

	/**
	 * 验证用户
	 * 
	 * @param input
	 * @return
	 */
	public boolean verifyUser(String input) {
		boolean ok = false;
		Session session = HbnUtils.getSession();
		Transaction tx = session.beginTransaction();
		String code = VerifyCodeUtils.getCode(input);
		Integer id = VerifyCodeUtils.getId(input);
		if (code == null || id == null)
			return false;
		User user = (User) session.get(User.class, id);
		if (user != null && user.getVerifyCode().equals(code)) {
			user.setVerify(true);
			ok = true;
		}
		tx.commit();
		session.close();
		return ok;
	}

	/**
	 * 登录<br>
	 * 根据邮箱和密码取得用户
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public User validateUser(String email, String password) {
		Session session = HbnUtils.getSession();
		Query query = session
				.createQuery("from User user where user.email=? and user.password=?");
		query.setParameter(0, email);
		// 密码MD5摘要
		query.setParameter(1, MD5Utils.md5(password));
		List<User> userList = query.list();
		session.close();
		if (userList.size() == 0) {
			return null;
		}
		return userList.get(0);

	}

	/**
	 *检测邮箱是否存在
	 * 
	 * @param email
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean validateEmail(String email) {
		Session session = HbnUtils.getSession();
		Query query = session
				.createQuery("select count(*) from User user where user.email=?");
		query.setParameter(0, email);
		List<Number> list = query.list();
		session.close();
		if (list.size() == 1 && list.get(0).intValue() == 0) {
			return true;
		} else {
			return false;
		}
	}

}
